package com.tianyadu.multi_module_demo.repository;

import com.tianyadu.multi_module_demo.domain.User;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @FileName: UserRepository
 * @Description: 用户数据控制层
 * @author: xueyj
 * @create: 2018-11-17 09:59
 */
@Repository
public class UserRepository {

    /**
      采用内存型存储 -- map
      */
    private final ConcurrentMap<Integer, User> userRepository = new ConcurrentHashMap<>();

    /** id   */
    private final static AtomicInteger idGenerator = new AtomicInteger();

    /**
      * @Description: 保存用户信息
      * @param:
      * @return: 保存成功，true；保存失败，false；
      * @author:
      * @date:   2018/11/17 10:00
      */
    public Boolean saveUser(User user) {
        // 自增长id
        Integer id = idGenerator.incrementAndGet();
        // 设置用户id信息
        user.setId(id);
        return userRepository.put(id, user) == null;
    }

    /**
      * @Description: 查询全部用户信息
      * @param:
      * @return:
      * @author:
      * @date:   2018/11/17 10:30
      */
    public Collection<User> findAll() {
        return userRepository.values();
    }
}
